<?php

namespace catchAdmin\externalGoods\controller;


use app\command\UserMessageQueue;
use cainiao\api\v1\Link;
use catchAdmin\api\model\Order as customsOrder;
use catchAdmin\api\model\OrderSon as customsOrderSon;
use catchAdmin\api\service\IndexService;
use catchAdmin\customs\excel\orderExport;
use catchAdmin\customs\model\HnOrder as hnOrderModel;
use catchAdmin\customs\model\HnOrderDetail;
use catchAdmin\customs\model\HnOrderDetail as hnOrderDetailModel;
use catchAdmin\customs\model\Order;
use catchAdmin\customs\model\Order as OrderModel;
use catchAdmin\customs\model\OrderSon;
use catchAdmin\customs\model\OrderSon as OrderSonModel;
use catchAdmin\customs\model\XsOrder;
use catchAdmin\customs\model\XsRefund;
use catchAdmin\externalGoods\excel\tenantOrdersExport;
use catchAdmin\externalGoods\model\Areas;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catchAdmin\externalGoods\model\GoodsRule;
use catchAdmin\externalGoods\model\GoodsRule as externalGoodsRuleModel;
use catchAdmin\externalGoods\model\Notify as externalNotifyModel;
use catchAdmin\externalGoods\model\OrderLogistics;
use catchAdmin\externalGoods\service\GoodsService as externalGoodsService;
use catchAdmin\externalGoods\model\TenantGoods as tenantGoodsModel;
use catchAdmin\externalGoods\model\CreditDeduction as CreditDeductionModel;
use catchAdmin\externalGoods\model\TenantGoodsRule as tenantGoodsRuleModel;
use catchAdmin\externalGoods\service\OrderService;
use catchAdmin\externalGoods\service\TenantGoodsService;
use catchAdmin\externalGoods\service\TenantOrderService;
use catchAdmin\permissions\model\Users;
use catchAdmin\stock\excl\stockExport;
use catcher\base\CatchRequest as Request;
use catcher\Code;
use catcher\library\excel\Excel;
use catcher\library\excel\reader\Reader;
use customs179\Service;
use houniao\api\v1\Order as HNOrderApi;
use hth\api\v1\Order as HthOrderApi;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\helper\Str;
use think\Request as ThinkRequest;
use catcher\CatchAdmin;
use catcher\CatchAuth;
use catcher\CatchResponse;
use houniao\api\v1\Goods as GoodsApi;
use think\Response;
use think\response\Json;
use xinsheng\api\v1\Pay;
use function Symfony\Component\Translation\t;
use catchAdmin\externalGoods\model\GoodsCustoms as GoodsCustomsModel;
use catchAdmin\externalGoods\model\ManifestTemplate as ManifestTemplateModel;

class TenantOrders extends CatchAdmin
{
    protected $_par = ['_merCode'=>'10000000863',
        '_public_key'=>'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJFkdpM39EbL36SwGUi6LBpXE9kVfX1z4r7NZkJUArJPGkblCs1gW919eAchOZhKOP9eBGAc6KTK0qArujjb+bg69Xl3sqJq0xZJBR1SJbLFI/rV7p0J92crC9ymiGsECM+7DkZS8UXLZeO1aSt59KTgnpfyOX7s4XjMnOS6MbPQIDAQAB'];


    public function __construct(OrderModel $orderModel, OrderSonModel $OrderSonModel,hnOrderModel $hnOrderModel,hnOrderDetailModel $hnOrderDetailModel)
    {
        $this->orderModel = $orderModel;
        $this->OrderSonModel = $OrderSonModel;
        $this->hnOrderModel  = $hnOrderModel;
        $this->hnOrderDetailModel = $hnOrderDetailModel;
    }

    /**
     * 订单列表
     *
     * @time 2020年01月09日
     * @param CatchRequest $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(): \think\response\Json
    {
        return CatchResponse::paginate($this->orderModel->getList2());
    }

    /**
     *
     * @time 2021/11/03 14:02
     * 修改进口业务申报订单
     * @param Request $request
     * @return Json
     */
    public function edit(CatchAuth $auth,Request $request): Response
    {
        $user = $auth->user();
        $type = $request->post('type');
        if (!$type) {
            return CatchResponse::fail('缺少参数');
        }
        if ($type === 1) {

            $orderId = $request->post('orderId');
            if (!$orderId) {
                return CatchResponse::fail('缺少参数');
            }
            //订单表
            $orderInfo = OrderModel::field('*')
                ->where([
                    'orderId' => $orderId,
                ])
                ->find()->toArray();
            $orderInfo['ConsigneeCode1'] = $orderInfo['ConsigneeCode'];
            $orderInfo['ConsigneeCode'] = preg_replace('/(\w{8})\w*(\w{4})/','$1******$2',$orderInfo['ConsigneeCode']);

            if (!$orderInfo) {
                return CatchResponse::fail('没有该订单');
            }
            //订单子表
            $orderInfo['goodsListStr'] = OrderSonModel::field('*')
                ->where([
                    'orderId'=>$orderInfo['orderId'],
                    'deleteStatus'=>0
                    ])
                ->select()
                ->each(function (&$item){
                    $where['deleted_at'] = 0;
                    $where['barcode'] = $item['barcode'];
                    if(!empty($item['RecordMaterialNo'])){
                        $where['record_material_no'] = $item['RecordMaterialNo'];
                    }
                    $material_info = Db::name('db_customs_record_material')->field('net_weight,gross_weight,origin_country_code,trade_country_code,currency_code,g_code,g_model,g_name,currency_code,unit,unit1,unit2,qty1,qty2,record_material_no')->where($where)->find();
                    if ($material_info){
                        foreach ($material_info as $key => $value){
                            $item[$key] = $value;
                        }
                    }
                })
                ->toArray();

            //扩展数据转成数组
            //$orderInfo['_return_data'] = json_decode($orderInfo['_return_data'],true);

            if (!$orderInfo['goodsListStr']) {
                return CatchResponse::fail('该订单,没有商品信息');
            }

            //查询渠道商 商品订单信息
            $_order_tenant_id = $orderInfo['tenant_id'];
            foreach ($orderInfo['order_goods'] as $_kkk => &$_od_value){
                $_od_value['_orderlist_info'] = [
                    'api_error'=> $orderInfo['goodsListStr'][$_kkk]['api_error'],
                    'api_post_status'=>$orderInfo['goodsListStr'][$_kkk]['api_post_status'],
                ];

                //商品总价 单价 goods_num goods_price 保留2位小数
                $_od_value['goods_amount'] = bcmul($_od_value['goods_price'],$_od_value['goods_num'],2);


                //跨境参数
                $goods_info = (new externalGoodsModel)->where('goods_spu',$_od_value['goods_spu'])->find();

                $_od_value['goods_name'] = $goods_info['goods_name'];
                $crossBorderParams = (new GoodsCustomsModel)->field([
                    'hg_itemRecordNo',
                    'hg_gcode',
                    'hg_gname',
                    'hg_gmodel',
                    'hg_originCountry',
                    'hg_qty1',
                    'hg_unit',
                    'hg_unit1',
                    'hg_unit2',
                    'manifest_template_id'
                ])
                    ->where('goods_id',$goods_info['id'])->find();
                
                //海关清单模版
                if(!empty($crossBorderParams['manifest_template_id'])){
                    $manifest_template = (new ManifestTemplateModel)->where(array('id' => $crossBorderParams['manifest_template_id']))->find();
                    $_od_value['manifest_template'] = $manifest_template;
                }else{
                    $_od_value['manifest_template'] = [];
                }

                if($crossBorderParams){
                    $_od_value = array_merge($_od_value,$crossBorderParams->toArray());
                }else{
                    $_od_value = array_merge($_od_value,[
                        'hg_itemRecordNo' => '',
                        'hg_gcode' => '',
                        'hg_gname' => '',
                        'hg_gmodel' => '',
                        'hg_originCountry' => '',
                        'hg_qty1' => '',
                        'hg_unit' => '',
                        'hg_unit1' => '',
                        'hg_unit2' => ''
                    ]);
                }
                //
                $_od_goods_detail = (new tenantGoodsModel)
                    ->field('trade_type_name,goods_img,goods_name,goods_spu,barcode,origin_name,brand_name,unit_name')
                    ->where('goods_spu',$_od_value['goods_spu'])
                    ->where('tenant_id',$_order_tenant_id)
                    ->find();
                $_od_value['_goods_detail'] = $_od_goods_detail;
                $_od_goods_attr = (new tenantGoodsRuleModel)
                    ->field('sku_name,sku_price')
                    ->where('goods_sku',$_od_value['sku_id'])
                    ->where('tenant_id',$_order_tenant_id)
                    ->find();
                $_od_value['_goods_rule'] = $_od_goods_attr;
            }

            $payment =  (new XsOrder)->field('dealId,checkOrg,checkOrgOrderNo,completeTime,_customsApply_data')->where([
                'merOrderId'=>$orderId,
                'status'=>1
            ])->find();
            if($payment){
                $payment = $payment->toArray();
                $payment['completeTime'] = date('Y-m-d H:i:s',strtotime($payment['completeTime']));
                if(empty($payment['_customsApply_data'])){
                    $payment['_customsApply_data'] = null;
                }else{
                    $payment['_customsApply_data']['completeTime'] = date('Y-m-d H:i:s',strtotime($payment['completeTime']));
                }
                //$payment['completeTime'] = date('Y-m-d H:i:s',strtotime($payment['completeTime']));
            }
            $orderInfo['xs_payment'] = $payment;

            return CatchResponse::success($orderInfo, '查询成功');
        } elseif ($type === 2) {
            $form = $request->post('form');
            if (!$form) {
                return CatchResponse::fail('缺少参数');
            }
            $info = json_decode(json_encode($form), true);

            //处理身份证 身份证前端展示6个*  存在*表示未作更改
            if(array_key_exists('ConsigneeCode',$info)&&strstr($info['ConsigneeCode'],"****")){
                unset($info['ConsigneeCode']);
            }
            $OrderSonModel = 0;
            foreach ($info['goodsListStr'] as $key => $value) {
                //以下为账册信息  不允许在此修改
                unset($value['net_weight']);
                unset($value['gross_weight']);
                unset($value['trade_country_code']);
                unset($value['origin_country_code']);
                unset($value['g_model']);
                unset($value['g_name']);
                unset($value['currency_code']);
                unset($value['unit']);
                unset($value['unit1']);
                unset($value['unit2']);
                unset($value['unit2']);
                unset($value['qty1']);
                unset($value['qty2']);
                unset($value['record_material_no']);
                unset($value['g_code']);
                $OrderSonModel += Db::name('db_customs_orderlist')->save($value);
            }
            unset($info['goodsListStr']);
            $orderModel = Db::name('db_customs_order')->save($info);
            if ($OrderSonModel > 0 || $orderModel > 0) {
                return CatchResponse::success([], '编辑成功');
            } else {
                return CatchResponse::fail('编辑失败');
            }
        } else {
            return CatchResponse::fail('未申明的类型');
        }
    }

    //下载模板
    public function downTemplate(Request $request)
    {
        $filename = $request->post('name');
        $file = "export/template/{$filename}.xlsx";
        if (is_file($file)) {
            return CatchResponse::success(['url' => 'http://' . $_SERVER['HTTP_HOST'] . '/' . $file]);
        } else {
            return CatchResponse::fail('模板文件不存在');
        }

    }
    /**
     * 写入日志
     * BASE_PATH 在入口文件设置
     */
    protected function writeLog($type,$text)
    {
        $now = date('Y-m-d H:i:s');
        $ip = request()->ip();
        $log_path = "log/api/{$type}/";
        $destination = $log_path.date('y_m_d').'.log';
        if(!is_dir($log_path)) {
            mkdir($log_path,0755,true);
        }
        error_log("[{$now}] ".$_SERVER['REMOTE_ADDR'].' '.$_SERVER['REQUEST_URI'].'  IP:'.$ip."\r\n{$text}\r\n", 3,$destination);
    }

    protected function commonReturn($type,$result)
    {
        //写入日志处理
        $this->writeLog($type, json_encode($result,JSON_UNESCAPED_UNICODE));

        if($result['code'] === 10000){
            return CatchResponse::success($result['data'], $result['msg'], $result['code']);

        }else{
            return CatchResponse::fail($result['msg'],$result['code']);

        }

    }

    public function import2(CatchAuth $auth,Request $request){

        $_XID = '';
            try {
                $user = $auth->user();
                $data = $request->post('list');

                //$data = json_decode($data,true);

                $creator_id = $user['id'];
                $tenant_id = $user['tenant_id'];

                $orderData = [];//主订单信息
                $orderSonData = [];//子订单信息

                $orderKeys = ['orderId','contactName','contactMobile','area_id','detailAddr','order_goods', 'amount', 'distributionfee', 'discount', 'realPayment','ebpCode','ebpName','paycomCode','paycomName','payOrderNo','contactAddr'];
                //保税
                $orderKeys_1 = ['contactCode','buyerName','ConsigneeCode','source_platform_no','pay_type','pay_time'];
                //香港直邮
                $orderKeys_4 = ['contactCode'];
                //海外直邮
                $orderKeys_5 = ['contactCode','id_card_front_img','id_card_back_img'];

                //$orderKeys = ['payerAccount','username','user_phone','area_id','user_address','orderId','order_goods', 'amount', 'distributionfee', 'discount', 'realPayment'];

                //订单商品字段
                $goodsKeys = ['goods_spu','sku_id','goods_num','goods_price'];
//        $goodsKeys_1 = ['goods_spu','sku_id','goods_num','goods_price'];

                $systGoodsModel = new externalGoodsModel;

                $msg = "";
                foreach ($data as $key => $value){
                    $_XID = $value['_XID'];
                    $checkValueResult = $this->check_fields($value, $orderKeys,true);//验证字段
                    //判断参数
                    if(!is_array($checkValueResult)){
                        throw new Exception($checkValueResult);
                    }

                    //2.判断订单号是否已经存在
                    $flag = Db::table('db_customs_order')
                        ->field('id')
                        ->where(['orderId' => $value['orderId'], 'deleteStatus' => 0, 'status' => 0, 'tenant_id' => $tenant_id])
                        ->find();
                    if($flag){
                        throw new Exception( '订单号'.$value['orderId'].'已存在');
                    }

                    $all_goods_spu_arr = array_column($value['order_goods'],'goods_spu');
                    $goods_spu_trade_type_arr = $systGoodsModel->where('goods_spu','in',$all_goods_spu_arr)->column('trade_type_id');
                    //3.订单商品，多个商品，判断都是同一类型
                    if(1 < count($value['order_goods'])){
                        $IndexService = new IndexService;
                        if($IndexService->checkTwoTradeType($goods_spu_trade_type_arr)){
                            throw new Exception('贸易类型错误、存在多个贸易类型');
                        }
                    }
//            if(!empty(array_intersect($goods_spu_trade_type_arr,[1,4,5]))){ //只有保税直供。 跨境商品，需要推送支付单
                    if(!empty(array_intersect($goods_spu_trade_type_arr,[1]))){ //只有保税直供。 跨境商品，需要推送支付单
                        $value['is_need_push_payment_order'] = 1;
                        $value['tradeType'] = '0004';
                    }else{
                        $value['tradeType'] = '0002';
                    }

                    foreach ($value['order_goods'] as $k => &$v){
                        $trade_type_id = $systGoodsModel->where('goods_spu',$v['goods_spu'])->value('trade_type_id');
                        if(1 == $trade_type_id){
                            $checkVResult1 = $this->check_fields($value, $orderKeys_1,true);//验证字段
                        }elseif (4 == $trade_type_id){
                            $checkVResult1 = $this->check_fields($value, $orderKeys_4,true);//验证字段
                        }elseif (5 == $trade_type_id){
                            $checkVResult1 = $this->check_fields($value, $orderKeys_5,true);//验证字段
                        }elseif(null == $trade_type_id){
                            throw new Exception('商品spu错误、或者商品贸易类型错误');
                        }else{
                            $checkVResult1 = [];
                        }

                        if(!is_array($checkVResult1)){
                            throw new Exception( $checkVResult1);
                            break 2;
                        }

                        $checkVResult = $this->check_fields($v, $goodsKeys,true);//验证字段
                        if(!is_array($checkVResult)){
                            throw new Exception($checkVResult);
                            break 2;
                        }

                        $goods_info = Db::table('db_syst_sync_goods_rule sr')
                            ->field('sr.sku_name,sg.goods_name,sr.goods_sku')
                            ->leftJoin('db_syst_sync_goods sg','sr.goods_id = sr.goods_id')
                            ->where('sr.goods_spu',$v['goods_spu'])
                            ->where('sr.sku_name',$v['sku_id'])
                            ->where('sr.deleted_at','=',0)
                            ->find();

                        if(!$goods_info){
                            throw new Exception("商品不存在spu（{$v['goods_spu']}）或sku（{$v['sku_id']}）");
                        }
                        $v['sku_id'] = $goods_info['goods_sku'];

                        $v['orderId'] = $value['orderId'];
                        $orderSonData[] = $v;
                    }
                    $value['tenant_id'] = $tenant_id;//电商商户
                    unset($value['goodsInfo']);

                    unset($value['goods_spu']);
                    unset($value['goods_num']);
                    unset($value['goods_price']);
                    unset($value['sku_id']);
                    $orderData[] = $value;
                    unset($value);
                }

                //dd($orderData);

                if($msg !== ""){
                    throw new Exception($msg);
                    //return [ 'code'=>Code::FAILED , 'msg'=> $msg ];
                }

                if(count($orderData)>0 && count($orderSonData)>0){
                    foreach ($orderData as &$value){
                        $_XID = $value['_XID'];
                        //dd($value);
                        $temp = [];
                        $temp['_order_type'] = 1;//订单类型 1候鸟订单
                        $temp['tenant_id'] = $value['tenant_id'];
                        $temp['orderId'] = $value['orderId'];//订单iD
//                $temp['source_platform_no'] = $value['source_platform_no'] ?? '';//申报订单编号

                        //订单默认日期
                        if(array_key_exists('orderDate',$value)){
                            $temp['orderDate'] =   date("Y-m-d H:i:s",strtotime($value['orderDate'])  ?? time());
                        }else{
                            $temp['orderDate'] = date("Y-m-d H:i:s");
                        }

                        $temp['create_time'] = strtotime($temp['orderDate']);


                        //收货地址
                        $area_id = Db::table('db_syst_sync_areas')->where('full_area_name',$value['contactAddr'])->value('area_id');
                        if(empty($area_id))  throw new Exception('收货地址区划错误，直辖市精确到街道，其他精确到区/县');

                        //如果是直辖市，直接取街道的地址
                        $area_son_id =  Db::table('db_syst_sync_areas')->where('pid',$area_id)->value('area_id');
                        if($area_son_id) $area_id = $area_son_id;
                        $value['area_id'] = $area_id;


                        $temp['HNACARD'] = array_key_exists('HNACARD',$value) ? $value['HNACARD'] : '0';
                        $temp['orderDate'] = $value['orderDate'];

                        //扩展数据
                        $temp['_ext_data'] = json_encode(array_merge($temp,$value));
                        $value = array_merge($value,$temp);

//                $value = $temp;
                        unset($value['_XID']);
                    }

                    foreach ($orderSonData as &$value){
                        $temp = [];
//                $temp['tenant_id'] = $value['tenant_id'];
                        $temp['orderId'] = $value['orderId'];
                        $temp['productId'] = $value['goods_spu'] . ',' . $value['sku_id'];
                        $temp['num'] = $value['goods_num'];

//                $goods_info = Db::table('db_syst_sync_goods_rule sr')
                        $goods_info = Db::table('db_tenant_goods_rule sr')
                            ->field('sr.sku_name,sg.goods_name,sg.is_sale,sg.stock,sr.sku_stock')
                            ->leftJoin('db_tenant_goods sg','sr.goods_id = sg.id')
                            ->where('sr.goods_spu',$value['goods_spu'])
                            ->where('sr.goods_sku',$value['sku_id'])
                            ->where('sr.tenant_id',$tenant_id)
                            ->where('sg.deleted_at',0)
                            ->find();
                        if(!$goods_info){
                            throw new Exception("商品【{$value['goods_spu']}】未添加、或商品不存在");
                        }

                        if($goods_info['is_sale'] != 1){
                            throw new Exception("商品已下架");
                        }

                        if($goods_info['stock'] <= 0 || $goods_info['sku_stock'] <= 0){
                            throw new Exception("当前商品规格库存不足");
                        }

                        //临时打个布丁
                        $_syst_goods = (new \catchAdmin\externalGoods\model\Goods())->where('goods_spu',$value['goods_spu'])->find();
                        if($_syst_goods['is_sale'] != 1){
                            throw new Exception("商品已下架～");
                        }
                        if($_syst_goods['stock'] <= 0){
                            throw new Exception("当前商品规格库存不足～");
                        }
                        $_syst_goods_rule = (new GoodsRule())
                            ->where('goods_spu',$value['goods_spu'])
                            ->where('goods_sku',$value['sku_id'])
                            ->find();
                        if(!$_syst_goods_rule){
                            throw new Exception("当前商品规格不存在、或已下架～");
                        }
                        if($_syst_goods_rule['sku_stock'] <= 0){
                            throw new Exception("当前商品规格库存不足～");
                        }
                        //布丁结束

                        $temp['goods_name'] = $goods_info['goods_name']. ' ' . $goods_info['sku_name'];
                        $temp['GCode'] = Db::table('db_syst_sync_goods')->where('goods_spu',$value['goods_spu'])->value('barcode');
                        $temp['price'] = $value['goods_price'];
                        $temp['goods_url'] = 'http://hg.qekj.net/#/goodsDetail?goods_spu=' . $value['goods_spu'];

                        $value = $temp;
                        //$value = array_merge($value,$temp);
                    }

                    //return $orderData;

                    // 启动事务
                    Db::startTrans();
                    try {
                        $res1 =  (new customsOrder)->limit(200)->insertAll($orderData);
                        $res2 =  (new customsOrderSon())->limit(200)->insertAll($orderSonData);
                        if($res1&&$res2){
                            // 提交事务
                            Db::commit();
                            return [ 'code'=>Code::SUCCESS , 'message'=> '新增成功' , 'data'=> []];
                        }else{
                            Db::rollback();
                            return [ 'code'=>Code::FAILED , 'message'=> '新增失败'];
                        }
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        return [ 'code'=>Code::FAILED , 'message'=> $e->getMessage()];
                    }
                }else{
                    return [ 'code'=>Code::FAILED , 'message'=> '没有订单或商品数据'];
                }

            } catch (\Exception $exception) {
                return json([
                    'code' => Code::PERMISSION_FORBIDDEN,
                    'message'  => $exception->getMessage(),
                    'data'=>$_XID
                ]);
                //return $this->commonReturn('order',['code'=>Code::FAILED, 'msg2'=> $exception->getMessage()]);
            }




    }

    //订单导入
    public function import(CatchAuth $auth,Request $request)
    {
        $user = $auth->user();
        // 获取表单上传文件
        $files = request()->file();
        $fields = [
            ['field' => 'orderId', 'label' => '订单号','require' => true],
            ['field' => 'orderDate', 'label' => '订单日期', 'require' => true],
            ['field' => 'declarer', 'label' => '订购人', 'require' => true],
            ['field' => 'declarer_id_card', 'label' => '订购人证件号', 'require' => true],
            ['field' => 'amount', 'label' => '订单金额', 'require' => true],
            ['field' => '_order_type', 'label' => '订单类型', 'require' => true],
            ['field' => 'username', 'label' => '收件人', 'require' => true],
            ['field' => 'contactAddr', 'label' => '收货地址', 'require' => true],
            ['field' => 'user_address', 'label' => '详细地址', 'require' => true],
            ['field' => 'user_phone', 'label' => '联系电话', 'require' => true],
            ['field' => 'goods_spu', 'label' => '商品编号', 'require' => true],
            ['field' => 'sku_id', 'label' => '规格名称', 'require' => true],
            ['field' => 'goods_num', 'label' => '商品数量', 'require' => true]
        ];
        $success = 0;
        // 启动事务
        Db::startTrans();
        try {
            //10M以下csv,xlsx,xls文件
            validate(['file' => 'fileSize:10485760|fileExt:csv,xlsx,xls'])->check($files);

            $requests = $request;

            $callable =  function ($data) use ($user,$fields,&$requests,&$success) {

                if($data <= 1) throw new Exception('没有需要导入的数据');

                //验证表头
                $import_field = $data[0];//头
                foreach ($fields as $k => $v) {
                    //验证表格头部是否模板字段
                    if (strpos($import_field[$v['field']], $v['label']) === false) {
//                        Db::rollback();
                        throw new Exception('模板表头' . $import_field[$v['field']] . '不匹配，请下载最新模板');
                    }
                }

                //验证数据
                $import_data = array_slice($data, 1);//数据
                foreach ($import_data as $key => $value) {
                    $params = [];
                    foreach ($fields as $k => $v) {
                        $params[$v['field']] = $value[$v['field']];
                        if(!$v['require']) continue;
                        //字段必填时
                        if(0 === strlen($value[$v['field']])){
                            Db::rollback();
                            throw new Exception('第' . ($key + 1) . '行' . $v['label'] . '不能为空');
                        }
                    }

                    $params['creator_id'] = $requests->user()->id;
                    $params['tenant_id'] = $user['tenant_id'];
                    $params['created_at'] = time();
                    $params['updated_at'] = time();


                    //验证数据合法性
                    $_deal_data =  $this->dealImportData($params);

                    //插入数据
                    $res1 =  (new customsOrder)->storeBy($_deal_data['order']);
                    $res2 =  (new customsOrderSon())->limit(200)->insertAll($_deal_data['order_son']);

                    if ($res1 && $res2){
                        $success++;
                    }else {
                        Db::rollback();
                        throw new Exception('第' . ($key + 1) . '行导入失败，请检查');
                    }
                }
                Db::commit();
            };

            $this->importExcl(array_column($fields, 'field'), $files['file'] ,$callable);

            return CatchResponse::success([],  '操作成功，成功导入' . $success . '条数据');
        } catch (Exception $e) {
            Db::rollback();
            return CatchResponse::fail('第' . ($success + 1) . '行导入失败，' . $e->getMessage());
        }
    }

    public function dealImportData($value){
        $temp = [];

        $temp['_order_type'] = 1;//订单类型 1候鸟订单
        $temp['tenant_id'] = $value['tenant_id'];
        $temp['orderId'] = $value['orderId'];//订单iD
        $temp['contactName'] = $value['username'];//收件人名字
        $temp['contactCode'] = $value['id_card'] ?? '';//收件人身份证
        $temp['contactMobile'] = $value['user_phone'] ?? '';//收件人手机
        $temp['buyerName'] = $value['declarer'] ?? '';//订购人
        $temp['ConsigneeCode'] = $value['declarer_id_card'] ?? '';//订购人身份正
        $temp['distributionfee'] = $value['amount_freight'] ?? '';//运费
        $temp['discount'] = $value['amount_discount'] ?? '';//优惠金额
        $temp['payOrderNo'] = $value['pay_no'] ?? '';//支付交易号
        $temp['orderDate'] = date("Y-m-d H:i:s",strtotime($value['orderDate'])  ?? time());
        //$temp['area_id'] =

        $flag = Db::table('db_customs_order')
            ->field('id')
            ->where(['orderId' => $value['orderId'], 'deleteStatus' => 0, 'status' => 0, 'tenant_id' => $value['tenant_id']])
            ->find();
        if($flag){
            throw new Exception('订单号'.$value['orderId'].'已存在');
        }

        //收货地址
        $area_id = Db::table('db_syst_sync_areas')->where('full_area_name',$value['contactAddr'])->value('area_id');
        if(empty($area_id))  throw new Exception('收货地址区划错误，直辖市精确到街道，其他精确到区/县');

        //如果是直辖市，直接取街道的地址
        $area_son_id =  Db::table('db_syst_sync_areas')->where('pid',$area_id)->value('area_id');
        if($area_son_id) $area_id = $area_son_id;

        //身份证
        if(!check_card($value['declarer_id_card'])) throw new Exception('身份证格式错误');

//        $isActiveAreaId = Db::table('db_syst_sync_areas')->where('pid',$value['area_id'])->count();
//        $isActiveAreaId2 = Db::table('db_syst_sync_areas')->where('area_id',$value['area_id'])->find();
//
////        dd(777);
//        if($isActiveAreaId > 0 || empty($isActiveAreaId2)){
//            throw new Exception('区域ID不存在，或者区域ID不是最下级');
//        }
//

        $temp['area_id'] = $area_id;//区县ID

        $temp['detailAddr'] = $value['user_address'] ?? '';//详细地址
        $temp['note'] = $value['remark'] ?? '';//备注
        $temp['realPayment'] = $value['realPayment'] ?? '';

        $temp['ebpCode'] = array_key_exists('ebpCode',$value) ? $value['ebpCode'] : '321266001M';
        $temp['ebpName'] = array_key_exists('ebpName',$value) ? $value['ebpName'] : '江苏东九健康科技有限公司';
        $temp['paycomCode'] = array_key_exists('paycomCode',$value) ? $value['paycomCode'] : '460116287K';
        $temp['paycomName'] = array_key_exists('paycomName',$value) ? $value['paycomName'] : '新生支付有限公司';
        $temp['tradeType'] = '0004';

        //扩展数据
        $temp['_ext_data'] = json_encode(array_merge($temp,$value));

        $order = array_merge($value,$temp);

        $goods_spu_arr = explode(',',$value['goods_spu']);
        $sku_id_arr = explode(',',$value['sku_id']);
        $goods_num_arr = explode(',',$value['goods_num']);

        if(count($goods_spu_arr) != count($sku_id_arr) || count($goods_spu_arr) != count($goods_num_arr)){
            throw new Exception('商品编码、规格、数量，参数数量不对应！');
        }

        $orderSonData = [];
        for ($i=0;$i<count($goods_spu_arr);$i++){
            $orderSonData[$i]['goods_spu'] = $goods_spu_arr[$i];
            $orderSonData[$i]['sku_id'] = $sku_id_arr[$i];
            $orderSonData[$i]['goods_num'] = $goods_num_arr[$i];
            $orderSonData[$i]['orderId'] = $value['orderId'];
        }
        $orderSonData2 = [];
        foreach ($orderSonData as &$value1){
            $temp1 = [];
//                $temp['tenant_id'] = $value['tenant_id'];
            $temp1['orderId'] = $value1['orderId'];
            $temp1['productId'] = $value1['goods_spu'] . ',' . $value1['sku_id'];
            $temp1['num'] = $value1['goods_num'];

            $goods_info = Db::table('db_syst_sync_goods_rule sr')
                ->field('sr.sku_name,sg.goods_name,sr.goods_sku')
                ->leftJoin('db_syst_sync_goods sg','sr.goods_id = sr.goods_id')
                ->where('sr.goods_spu',$value1['goods_spu'])
                ->where('sr.sku_name',$value1['sku_id'])
                ->find();

            if(!$goods_info){
                throw new Exception("商品不存在spu（{$value1['goods_spu']}）或sku（{$value1['sku_id']}）");
            }

            $value1['sku_id'] = $goods_info['goods_sku'];

            //$temp1['sku_id'] = $goods_info['goods_sku'];
            $temp1['goods_name'] = $goods_info['goods_name'] . $goods_info['sku_name'];

            $temp1['GCode'] = Db::table('db_syst_sync_goods')->where('goods_spu',$value1['goods_spu'])->value('barcode');
            $temp1['price'] = Db::table('db_syst_sync_goods_rule')->where('goods_sku',$value1['sku_id'])->value('sku_price');

            $orderSonData2[] = [
                'goods_spu'=>$value1['goods_spu'],
                'sku_id'=>$value1['sku_id'],
                'goods_num'=>$value1['goods_num'],
                'orderId'=>$value1['orderId'],
                'price'=>$temp1['price'],
            ];

            $value1 = $temp1;
            //$value = array_merge($value,$temp);
        }

        $order['order_goods'] = $orderSonData2;

        return ['order'=>$order,'order_son'=>$orderSonData];
    }

    //新生支付-预付卡推送
    public function yfkApply($id,CatchAuth $auth, Request $request){
        $user = $auth->user();
        $tenant_id = $user['tenant_id'];

        $where = [
            'tenant_id'=>$tenant_id,
            'id'=>$id
        ];
        $order  = (new customsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where($where)
            ->find();

        if(!$order){
            return CatchResponse::fail('订单不存在');
        }
        $value = $order->toArray();

        if(0 == $value['is_need_push_payment_order']){
            //非跨境商品，利润上讲，不需要推送支付单单
            return CatchResponse::fail('该订单无需使用预付卡推单~');
        }

        $apiPayData = [];
        $apiPayData['merOrderId'] = $value['orderId'];
        $apiPayData['displayName'] = '跨进电商商品';
//        $apiPayData['displayName'] = '荔枝云集订单';
        $apiPayData['goodsName'] = '跨进电商商品';
//        $apiPayData['goodsName'] = '【无盒福利】HR赫莲娜 绿宝瓶眼部精华 15ML （有效期：';
        $apiPayData['goodsCount'] = array_sum(array_column($value['order_goods'],'goods_num'));
        $apiPayData['orderAmount'] =  (int) ($value['realPayment'] * 100);
        $apiPayData['orderCurrencyCode'] = 'CNY';

        if(1 == $value['is_need_push_payment_order']){
            $apiPayData['tradeType'] = '0004'; //跨境
            $apiPayData['goodsType'] = '06';//化妆品
            $apiPayData['customerName'] = $value['buyerName'];
            $apiPayData['customerIdNo'] = $value['ConsigneeCode'];
            $apiPayData['customerTel'] = $value['contactMobile'];
        }else{ //即便是普通商品，走预付卡支付 也要0004 所以也要手机号 身份证 姓名
            //这里身份证直接走 李楠法人的。
            $goodsTypeOptions = ['00','01','02','03','04','05','06','07'];
            $apiPayData['tradeType'] = '0004'; //非跨境
            //$apiPayData['goodsType'] = $goodsTypeOptions[mt_rand(0,7)];
            $apiPayData['goodsType'] = '06';//化妆品
            $apiPayData['displayName'] = '普通电商商品';
            $apiPayData['goodsName'] = '普通电商商品';
            if(empty( $value['buyerName']) || empty($value['ConsigneeCode'])){
                $apiPayData['customerName'] = '李楠';
                $apiPayData['customerIdNo'] = '320106198110272854';
                $apiPayData['customerTel'] = $value['contactMobile'];
            }else{
                $apiPayData['customerName'] = $value['buyerName'];
                $apiPayData['customerIdNo'] = $value['ConsigneeCode'];
                $apiPayData['customerTel'] = $value['contactMobile'];
            }
        }

//        $apiPayData['tradeType'] = $order['tradeType']; //跨境
//        $apiPayData['goodsType'] = '06';//化妆品
//        $apiPayData['customerName'] = $value['buyerName'];
//        $apiPayData['customerIdNo'] = $value['ConsigneeCode'];
//        $apiPayData['customerTel'] = $value['contactMobile'];


        $apiPayData['payType'] = '10';//预付卡
        $apiPayData['orgCode'] = 'HNACARD';//预付卡
        $apiPayData['payCurrencyCode'] = 'CNY';
        $apiPayData['settleCurrencyCode'] = 'CNY';
        $apiPayData['shareFlag'] = '0';
        $apiPayData['returnUrl'] = 'http://cross.qekj.net/callback/xinsheng';
        $apiPayData['noticeUrl'] = 'http://cross.qekj.net/callback/xinsheng';
        $apiPayData['customerType'] = '1'; // 非跨境单可以直接不要
        $apiPayData['declareCheck'] = '0';


        //文档参数顺序
        $req_key = ['merOrderId','displayName','goodsName','goodsCount','goodsType','orderAmount','orderCurrencyCode','tradeType',
            'payType','orgCode','payerAccount','payCurrencyCode','settleCurrencyCode','shareFlag','subMerchantOrderDetails','returnUrl',
            'noticeUrl','platformId','customerId','customerType','customerName','customerIdNo','customerTel'
            ,'bankCardNo','bankCardType','expireData','cvn','remark','reserve1','reserve2','preOrderFlag','declareCheck'];
        //新生支付，参数有顺序要求。必须按照文档来
        $apiPayData = getAfterSortByKeys($req_key,$apiPayData);

        //return $apiPayData;

        //查询子商户 code public
        if('10043' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIxqxcsyOxtdUgYFh49Xbs+wFjpRMYmiyUxxkvq+uHziUWIAOoW0bBnonWx7I358/zQItd7c4rFlidFpoS2XVG/OBTWGVfu8LjSLeSv650ldnDXYSBRtYlI6PqpjHeYxr0vUjiVFnc9yfT0yXiFBHGCDBOKH20P/1LNlvUxexmgwIDAQAB';
            $_par['_merCode'] = '10000000889';
        }elseif ('10050' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpnB5TpxPqMZwgarw1xNSTxb2nGeBxlCJ8WwInbeNs52s7w6qBmZJVJN456WoRWeI4mf2WZ7PfVmE+iY+LLjAQ+YZ07A6AI0FtKGIQM4lCtgbjYbi/yCrqwG+Y1odNZkUD+0zHwsJnLEovUx/Ah03Z2wEaY6pidaR+v9ERK/XmiwIDAQAB';
            $_par['_merCode'] = '10000000890';
        }elseif ('10143' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsrshGKOzARNQ65zlZ4izJPUGYTQOINg++2WOZ//ECkmnJqPinSs4ou4NXqnOSBs255JHLO5Xx3d/OXLZ03bg5tUWYSLBkCAAmcBljyMFFOD6hUN8QBd9NAEbspw5uXegqDO/ZAtENwg8bY5at5feagUTEP710jsBgBFkGPnjiXwIDAQAB';
            $_par['_merCode'] = '10000000938';
        }elseif ('10144' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTDxEfIEiCZ6DF4xxF45Q2tuz+YXIfneLct4dGrVeyvfJ0SGSF44LVjFbnn2/Zgo6+eOBPtqkk5Xhz0t6UM6owXNBsQ0+f54p8vIDixfDFB1EPYeGrNAD7yneZnRQrVk5C58n6FjRyz8DVa4C94mGf1MPQvt43inEP5K/Sj6hCZQIDAQAB';
            $_par['_merCode'] = '10000000937';
        }elseif ('10161' == $tenant_id || '10159' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDkLJf6Rh/iQ7VO6jqNzD5AneS++Jh1kkjtbdflXeyBnh70AFGsHgLa70P8TvUfywKqgkY5Vq8+psw7ROhZjyqMqC+rz+M6zpf43R2lvTuCAP3wbbtBdP25QHqIgVTXAVvDcX+YNn+YY2bbB7/IUXurhEOUmEKUOC5YT5cUMSG1XwIDAQAB';
            $_par['_merCode'] = '10000001001';
        }

        $xinshengApi = new Pay($_par);

        Db::startTrans();
        try {
            $result = $xinshengApi->apiPay($apiPayData);

            $update =  [
                'pay_time'=>time(),
//                    'push_status'=>'已支付',
                'push_status'=>'未推送',
//                'xs_status'=>$result['content']['status'],
                'dealId'=>$result['content']['dealId'],
                'payOrderNo'=>$result['content']['dealId'],
//                '_random_orderId'=>$result['head']['orderId']
            ];
            $order->save($update);

            $insert = array_merge($apiPayData,[
                '_ext_data'=>$apiPayData,
                '_return_data'=>$result['content'],//接口返回内容保存一份
                'status'=>$result['content']['status'],//支付状态
                'dealId'=>$result['content']['dealId'],//支付系统交易号
                'orderId'=>$result['head']['orderId'],
                'payAmount' =>  number_format($result['content']['payAmount'] / 100 ,2),
                'completeTime' => $result['content']['completeTime'],
                'tenant_id'=>$tenant_id,
//                'payInfo'=>$result['content']['payInfo'],//用于小程序的支付参数
                'toReturnUrl'=>'1',//客户回掉地址
                'toNoticeUrl'=>'1',//客户回掉地址
            ]);

            $last_result = $result['content'];
            $last_result['initialRequest'] = $apiPayData;//原始请求
            $last_result['initialResponse'] = $result;//原始响应

            $suc = (new XsOrder)->save($insert);

            if($suc){
                Db::commit();
                return CatchResponse::success($result,'预付卡支付成功');
            }else{
                Db::rollback();
                return CatchResponse::fail('预付卡支付失败');
            }
        }catch (\Exception $e ){
            Db::rollback();
            return CatchResponse::fail($e->getMessage());
        }
    }

    //新生支付-报关申请
    public function customsApply($id,CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        $tenant_id = $user['tenant_id'];

        $order  = (new customsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('id',$id)
            ->find();

        if(!$order)  return CatchResponse::fail('订单不存在');

        $xs_order = (new XsOrder)
            ->where('merOrderId',$order['orderId'])
            ->where('status',1)->find();

        if(!$xs_order) return CatchResponse::fail('新生订单不存在、或未支付');

        if('0002' == $order->tradeType || '0' == $order->is_need_push_payment_order){
            return CatchResponse::fail('该订单贸易类型不支持推送支付单');
        }


        $data = [
            'merOrderId'=>$order['orderId'],
            'eCompanyCode'=>$order['ebpCode'],
            'eCompanyName'=>$order['ebpName'],
            'payTransactionNo'=>$order['payOrderNo'],
            'actionType'=> '1',//新增，2修改
            'payerName'=>$order['buyerName'],//支付人姓名
            'payerType'=>'01',//
            'payerId'=>$order['ConsigneeCode'],//证件号
            'noticeUrl'=>"http://cross.qekj.net/callback/xinsheng",
            'currencyCode'=>"CNY",
            'eportCode'=>"00"
        ];

        //文档参数顺序
        $req_key = ['eportCode','merOrderId','currencyCode','eCompanyCode','eCompanyName','payTransactionNo','actionType','payerName','payerType','payerId','payerPhoneNumber','orderDetails','noticeUrl'];
        //新生支付，参数有顺序要求。必须按照文档来
        $data = getAfterSortByKeys($req_key,$data);

        //查询子商户 code public
        if('10043' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIxqxcsyOxtdUgYFh49Xbs+wFjpRMYmiyUxxkvq+uHziUWIAOoW0bBnonWx7I358/zQItd7c4rFlidFpoS2XVG/OBTWGVfu8LjSLeSv650ldnDXYSBRtYlI6PqpjHeYxr0vUjiVFnc9yfT0yXiFBHGCDBOKH20P/1LNlvUxexmgwIDAQAB';
            $_par['_merCode'] = '10000000889';
        }elseif ('10050' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpnB5TpxPqMZwgarw1xNSTxb2nGeBxlCJ8WwInbeNs52s7w6qBmZJVJN456WoRWeI4mf2WZ7PfVmE+iY+LLjAQ+YZ07A6AI0FtKGIQM4lCtgbjYbi/yCrqwG+Y1odNZkUD+0zHwsJnLEovUx/Ah03Z2wEaY6pidaR+v9ERK/XmiwIDAQAB';
            $_par['_merCode'] = '10000000890';
        }elseif ('10143' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsrshGKOzARNQ65zlZ4izJPUGYTQOINg++2WOZ//ECkmnJqPinSs4ou4NXqnOSBs255JHLO5Xx3d/OXLZ03bg5tUWYSLBkCAAmcBljyMFFOD6hUN8QBd9NAEbspw5uXegqDO/ZAtENwg8bY5at5feagUTEP710jsBgBFkGPnjiXwIDAQAB';
            $_par['_merCode'] = '10000000938';
        }elseif ('10144' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTDxEfIEiCZ6DF4xxF45Q2tuz+YXIfneLct4dGrVeyvfJ0SGSF44LVjFbnn2/Zgo6+eOBPtqkk5Xhz0t6UM6owXNBsQ0+f54p8vIDixfDFB1EPYeGrNAD7yneZnRQrVk5C58n6FjRyz8DVa4C94mGf1MPQvt43inEP5K/Sj6hCZQIDAQAB';
            $_par['_merCode'] = '10000000937';
        }elseif ('10161' == $tenant_id || '10159' == $tenant_id){
            $_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDkLJf6Rh/iQ7VO6jqNzD5AneS++Jh1kkjtbdflXeyBnh70AFGsHgLa70P8TvUfywKqgkY5Vq8+psw7ROhZjyqMqC+rz+M6zpf43R2lvTuCAP3wbbtBdP25QHqIgVTXAVvDcX+YNn+YY2bbB7/IUXurhEOUmEKUOC5YT5cUMSG1XwIDAQAB';
            $_par['_merCode'] = '10000001001';
        }

        //实例化新生api类
        $xinshengApi = new Pay($_par);

        Db::startTrans();
        try {
            $orderService = new TenantOrderService();
            $creditDeductResult = $orderService->creditDeductByOrderPk($id);
            if($creditDeductResult['status'] != 1){// 授信额度扣款失败了
                throw new Exception($creditDeductResult['msg']);
            }

            //2.调用新生的
            $result = $xinshengApi->customsApply($data);

            //$order1 = (new XsOrder)->find($order->xs_pk);
            $xs_order->customsApply_param = $data;//报关请求参数
            $xs_order->customsApply_return = $result['content'];//报关同步返回的参数
            $xs_order->customsApply_status = 1;//已申请
            $xs_order->toNoticeUrl2 = '1';//报关申请-异步通知地址

            $suc =  $xs_order->save();
            //return CatchResponse::success($result,'退款申请成功');

            if($suc) {
                Db::commit();
                return  CatchResponse::success($result['content'],'提交成功');
            } else{
                throw new Exception('网络错误');
            }
        }catch (\Exception $e ){
            Db::rollback();
            return CatchResponse::fail('提交失败 ' . $e->getMessage());
        }
    }

    //新生支付--退款
    public function xsRefund($id,CatchAuth $auth, Request $request){
        $user = $auth->user();
        $data = $request->post();

        unset($data['creator_id']);

//        $keys = ['merOrderId','oldDealId','amount','currency','noticeUrl'];
//        $value = $this->check_fields($data, $keys, true);//验证字段
//        //判断参数
//        if(!is_array($value)){
//            return [ 'code'=>Code::FAILED , 'msg'=> $value];
//        }

        $data['merOrderId'] = Str::random(20,1);

        $order  = (new customsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('dealId',$data['oldDealId'])
            ->find();

        $refund = (new XsRefund)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('merOrderId',$data['merOrderId'])
            ->find();

        if(!$order){
            return CatchResponse::fail("支付交易号{$data['oldDealId']}不存在");
        }

        if($refund){
            return CatchResponse::fail("退款订单编号{$data['merOrderId']}已存在");
        }

        $xinshengApi = new Pay();
        $data['noticeUrl'] = "http://cross.qekj.net/callback/xinsheng";

        try {
            $orderId = Str::random(20,1);
            $result = $xinshengApi->refund($orderId,$data);
            $refundData = [
                'orderId'=>$orderId,
                'merOrderId'=>$data['merOrderId'],
                'oldDealId'=>$data['oldDealId'],
                'status'=>$result['content']['status'],
                'responseDesc'=>$result['content']['responseDesc'],
                'refundOrderNo'=>$result['content']['refundOrderNo'],
                'oldOrderAmount'=>$result['content']['oldOrderAmount'],
                'refundAmount'=>$result['content']['refundAmount'],
                'refundFee'=>$result['content']['refundFee'],
                'tenant_id'=>$user['tenant_id'],
                '_return_data'=>$result['content']
            ];

            $refundModel = (new XsRefund)->save($refundData);

            return CatchResponse::success($result,'退款申请成功');
        }catch (\Exception $e ){
            return CatchResponse::fail($e->getMessage());
        }
    }

    //候鸟--2024-12-03备份
    public function createOrder_bak($id,CatchAuth $auth)
    {
        $user = $auth->user();

        $where = [];
        if(0 !== $user['tenant_id']){
            $where['o.tenant_id'] = $user['tenant_id'];
        }

        $order = $this->orderModel
            ->alias('o')
            ->field('o.orderId as source_order_no,
              contactName as username,
              contactMobile as user_phone,
                is_pay,
              contactCode as id_card,
                id_card_front_img,
                id_card_back_img,
               buyerName as declarer, 
               ConsigneeCode as declarer_id_card,
              distributionfee as amount_freight,
              discount as amount_discount,
               realPayment as amount_paid_in,
                pay_type,
              xs.checkOrgOrderNo as pay_no, 
                create_time, 
                pay_time, 
                area_id, 
               detailAddr as user_address,
                order_goods,
               o.tenant_id,
                push_status,
                source_platform_no as zfddh,
                ebpCode as customs_platform_code,
                ebpName as customs_platform_name,
                payOrderNo as source_platform_no,
                o.orderId as source_platform_no,
                o.remark')
            ->leftJoin('db_customs_xs_order xs','xs.merOrderId = o.orderId')
            ->where($where)
            ->find($id);

        if (!$order) {
            return CatchResponse::fail('订单不存在');
        }

        if ($order['push_status'] == '已推送') {
            return CatchResponse::fail('订单已经推送，不可重复操作');
        }

        $data = $order->toArray();
        //$data['order_goods'] = json_decode($order['order_goods'],true);

        foreach ($data['order_goods'] as $key => &$value) {
            if ($key == 'orderId') {
                unset($data['order_goods'][$key]['orderId']);
            }
        }


        if($data['pay_type'] != 3){//代表自己推支付单
            $data['pay_no'] = $data['zfddh'];
        }
        unset($data['tenant_id'], $data['creator_id'], $data['push_status'],$data['zfddh']);


        if(!empty($data['declarer']) &&  !empty($data['declarer_id_card'])){//存在订购人
            if(empty($data['username']) || empty($data['id_card'])){//3种跨境都需要 收件人+身份，如果没有填写的问题
                $data['id_card'] = $data['declarer_id_card'];
                $data['username'] = $data['declarer'];
            }
        }

        $orderService = new TenantOrderService();


        $orderSonModel = new OrderSon;

        $orderlistResult = $orderSonModel
            ->where('api_post_status','<>',1)
            ->where('orderId',$order['source_order_no'])->select();

        if(!$orderlistResult){
            return CatchResponse::fail('明细单错误');
        }
        $orderlistResult = $orderlistResult->toArray();


        Db::startTrans();
        try {
            $creditDeductResult = $orderService->creditDeductByOrderPk($id);
            if($creditDeductResult['status'] != 1){// 授信额度扣款失败了
                throw new Exception($creditDeductResult['msg']);
            }

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail($exception->getMessage());
        }

//        return $orderlistResult;

        $error = 0;
        $error_msg = '';
        foreach ($orderlistResult as $k=>$v){
            Db::startTrans();
            try {
                $supplier_id = $v['goods_supplier_id'];
                $orderlist_id = $v['id'];
                if(1 ==  $supplier_id){
                    //return

                    //重新调整数据
                    $data_supplier1 = $orderService->hnFormatApiOrderSonData($orderlist_id,$data);

                    $result = (new HNOrderApi())->createOrder($data_supplier1)['data'];//候鸟-提交数据
                    $orderService = new TenantOrderService();
                    $res = $orderService->hnCreateOrderSave($orderlist_id,$result['order_items']);//候鸟-保存数据
                }elseif (2 == $supplier_id){

                    //格式化数据
                    $data_supplier2 = $orderService->hthFormatApiOrderSonData($orderlist_id,$data);
                    $result = (new HthOrderApi)->createOrder($data_supplier2)['data'];//海淘汇-提交数据
                    //拉商品详情
//                $orderInfo = (new HthOrderApi)->info(['order_sn'=>'THD2408261758017129'])['data'];
                    $orderInfo = (new HthOrderApi)->info(['order_sn'=>$result['order_sn']])['data'];

                    $orderService = new TenantOrderService();
                    $res = $orderService->hthCreateOrderSave($orderlist_id,$orderInfo);//海淘汇-保存数据
                }

                if($res['status'] != 1){// 保存数据失败
                    throw new Exception($res['msg']);
                }

                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $orderSonModel->where('id',$orderlist_id)->save([
                    'api_post_status'=>-1,
                    'api_error'=>$exception->getMessage()
                ]);
                ++$error;
                $error_msg = $exception->getMessage();
            }
        }

        if($error > 0){
            $str = "推送失败[$error_msg]，订单失败数量：{$error}";
            return CatchResponse::fail($str);
        }else{
            return CatchResponse::success('OK');
        }
    }

    //候鸟--创建订单
    public function createOrder($id,CatchAuth $auth)
    {
        $user = $auth->user();

        $where = [];
        if(0 !== $user['tenant_id']){
            $where['o.tenant_id'] = $user['tenant_id'];
        }

        $order = $this->orderModel
            ->alias('o')
            ->field('o.orderId as source_order_no,
              contactName as username,
              contactMobile as user_phone,
                is_pay,
              contactCode as id_card,
                id_card_front_img,
                id_card_back_img,
               buyerName as declarer, 
               ConsigneeCode as declarer_id_card,
              distributionfee as amount_freight,
              discount as amount_discount,
               realPayment as amount_paid_in,
                pay_type,
              xs.checkOrgOrderNo as pay_no, 
                create_time, 
                pay_time, 
                area_id, 
               detailAddr as user_address,
                order_goods,
               o.tenant_id,
                push_status,
                source_platform_no as zfddh,
                ebpCode as customs_platform_code,
                ebpName as customs_platform_name,
                payOrderNo as source_platform_no,
                o.orderId as source_platform_no,
                o.remark')
            ->leftJoin('db_customs_xs_order xs','xs.merOrderId = o.orderId')
            ->where($where)
            ->find($id);

        if (!$order) {
            return CatchResponse::fail('订单不存在');
        }

        if ($order['push_status'] == '已推送' || $order['push_status'] == '订单处理中') {
            return CatchResponse::fail('订单已经推送，不可重复操作');
        }

        $data = $order->toArray();
        //$data['order_goods'] = json_decode($order['order_goods'],true);

        foreach ($data['order_goods'] as $key => &$value) {
            if ($key == 'orderId') {
                unset($data['order_goods'][$key]['orderId']);
            }
        }


        if($data['pay_type'] != 3){//代表自己推支付单
            $data['pay_no'] = $data['zfddh'];
        }
        unset($data['tenant_id'], $data['creator_id'], $data['push_status'],$data['zfddh']);


        if(!empty($data['declarer']) &&  !empty($data['declarer_id_card'])){//存在订购人
            if(empty($data['username']) || empty($data['id_card'])){//3种跨境都需要 收件人+身份，如果没有填写的问题
                $data['id_card'] = $data['declarer_id_card'];
                $data['username'] = $data['declarer'];
            }
        }

        $orderService = new TenantOrderService();


        $orderSonModel = new OrderSon;

        $orderlistResult = $orderSonModel
            ->where('api_post_status','<>',1)
            ->where('orderId',$order['source_order_no'])->select();

        if(!$orderlistResult){
            return CatchResponse::fail('明细单错误');
        }
        $orderlistResult = $orderlistResult->toArray();


        Db::startTrans();
        try {
            $creditDeductResult = $orderService->creditDeductByOrderPk($id);
            if($creditDeductResult['status'] != 1){// 授信额度扣款失败了
                throw new Exception($creditDeductResult['msg']);
            }

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail($exception->getMessage());
        }

//        return $orderlistResult;

        $error = 0;
        $error_msg = '';
        foreach ($orderlistResult as $k=>$v){
            Db::startTrans();
            try {
                $supplier_id = $v['goods_supplier_id'];
                $orderlist_id = $v['id'];
                if(1 ==  $supplier_id){
                    //return

                    //重新调整数据
                    $data_supplier1 = $orderService->hnFormatApiOrderSonData($orderlist_id,$data);


                    $result = (new HNOrderApi())->createOrder($data_supplier1)['data'];//候鸟-提交数据
                    $orderService = new TenantOrderService();
                    $res = $orderService->hnCreateOrderSave($orderlist_id,$result['order_items']);//候鸟-保存数据
                }elseif (2 == $supplier_id){

                    //格式化数据
                    $data_supplier2 = $orderService->hthFormatApiOrderSonData($orderlist_id,$data);
                    $result = (new HthOrderApi)->createOrder($data_supplier2)['data'];//海淘汇-提交数据

                    //拉商品详情
//                $orderInfo = (new HthOrderApi)->info(['order_sn'=>'THD2408261758017129'])['data'];
                    $orderInfo = (new HthOrderApi)->info(['order_sn'=>$result['order_sn']])['data'];
                    $orderService = new TenantOrderService();
                    $res = $orderService->hthCreateOrderSave($orderlist_id,$orderInfo);//海淘汇-保存数据
                }elseif (3 == $supplier_id){
                    //格式化数据
                    $data_supplier3 = $orderService->xyFormatApiOrderSonData($orderlist_id,$data);

//                    print_r($data_supplier3);
//                    throw new Exception(33);

                    $xyb2b = new \xyb2b\api\v1\Link();
                    $result = $xyb2b->add_custom_order_v2($data_supplier3);//行云-提交数据

                    if(array_key_exists('merchant_order_id',$result) && !empty($result['merchant_order_id'])){
                        (new Order)->updateBy($id,['push_status'=>'订单处理中']);
                        $res['status'] = 1;
                        $res['msg'] = '处理成功';
                    }else{
                        $res['status'] = -1;
                        $res['msg'] = '订单处理失败';
                    }
                }

                if($res['status'] != 1){// 保存数据失败
                    throw new Exception($res['msg']);
                }

                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $orderSonModel->where('id',$orderlist_id)->save([
                    'api_post_status'=>-1,
                    'api_error'=>$exception->getMessage()
                ]);
                ++$error;
                $error_msg = $exception->getMessage();
            }
        }

        if($error > 0){
            $str = "推送失败[$error_msg]，订单失败数量：{$error}";
            return CatchResponse::fail($str);
        }else{
            return CatchResponse::success('OK');
        }
    }

    //候鸟--手动修改订单状态-通知下游
    public function modifyOrder($id,CatchAuth $auth ,Request $request){
        $callback = $request->post('callback');
        $push_status = $request->post('push_status');
        //$order_status = $request->post('push_status_num');
        $params = $request->param();


        $orderStatusOptions = [
            -3=>'异常订单',
            -2=>'是待付款',
            -1=>'已取消',
            0=>'待发货',
//            1=>'已发货、待收货',
            1=>'已发货',
            2=>'已收货',
            3=>'海关审核中 | 仓库分拣打包',
            5=>'已完成',
            501=>'退货退款',
        ];
        $orderStatusOptions = array_flip($orderStatusOptions);

        $order_status = array_key_exists($push_status,$orderStatusOptions) ? $orderStatusOptions[$push_status] : '未知';

        Db::startTrans();
        try {
            $logisticsModel = new OrderLogistics;
            $_order = $this->orderModel
                ->field('o.*,od.order_no')
                ->alias('o')
                ->leftJoin('db_customs_hn_order_detail od','od.order_id = o.id and (od.deleted_at = 0 or od.deleted_at = null)')
                ->find($id);

            $_order_no = $_order['order_no'];

            $goods_spu = $_order['order_goods'][0]['goods_spu'];
            $sku_id = $_order['order_goods'][0]['sku_id'];
            $goods_num = $_order['order_goods'][0]['goods_num'];

            $goods_info = (new tenantGoodsModel())->where('goods_spu',$goods_spu)->where('tenant_id',$_order['tenant_id'])->find();
            if(empty($_order_no)){//不存在
                $_order_no = "V" .  date('ymdHis') . mt_rand(1000,9999);

                $goods_rule_info = (new tenantGoodsRuleModel())->where('goods_sku',$sku_id)->where('tenant_id',$_order['tenant_id'])->find();
                HnOrderDetail::create([
                    'order_id'=>$_order['id'],
                    'order_no'=>$_order_no,
                    'goods_spu'=>$goods_spu,
                    'sku_id'=>$sku_id,
                    'goods_name'=>$goods_info['goods_name'],
                    'goods_sku'=>$sku_id,
//                    'order_status'=>-1,
                    'order_status'=>$order_status,
                    'mall_order_status'=>$order_status,
                    'is_pay'=>1,
                    'goods_money'=>$goods_rule_info['cost_price'] * $goods_num,
                    'total_money'=>$goods_rule_info['cost_price'] * $goods_num,
                    'tenant_goods_money'=>$goods_rule_info['sku_price'] * $goods_num,
                    'tenant_total_money'=>$goods_rule_info['sku_price'] * $goods_num,
                    'real_total_money'=>$goods_rule_info['cost_price'] * $goods_num,
                    'goods_price'=>$goods_rule_info['cost_price'],
                    'tenant_goods_price'=>$goods_rule_info['sku_price'],
                    'goods_num'=>$goods_num,
//                    'source_order_no'=>$_order['orderId'],
                    'source_order_no'=>$_order['orderId'] . "_1",
                    'main_order_id'=>$_order['orderId'],
                    'tenant_id'=>$_order['tenant_id']
                ]);
            }else{
                HnOrderDetail::update([
                    'order_status'=>$order_status,
                    'mall_order_status'=>$order_status],['order_no'=>$_order_no]);
            }

            $_order->push_status = $push_status;

            if($push_status === '已发货'){//保存物流单号
                /***
                $_order->express_no = $params['express_no'];
                $_order->express_company = $params['express_name'];
                 **/

                $logisticsModel::destroy([
                    'order_id'=>$_order['orderId'] . "_1"
                ]);
                $logisticsModel::create([
                    'main_order_id'=>$_order['orderId'],
                    'order_id'=>$_order['orderId'] . "_1",
                    'order_no'=>$_order_no,
                    'express_no'=>$params['express_no'],
                    'express_name'=>$params['express_name'],
                    'express_code'=>$params['express_code'],
                    'delivery_time'=>date('Y-m-d H:i:s') ,
                    'supplier_id'=>$goods_info['supplier_id']
                ]);
            }

            $_order->save();

            //return !in_array($push_status, ['已取消','退货退款']);

            $req_data = [];
            $msg = 'success';

            if(in_array($push_status, ['已取消','退货退款'])){//退回授信额度
                if($id > 113142){
                    $orderService = new TenantOrderService();
                    $creditDeductResult = $orderService->creditBackByOrderPk($id);
                    if($creditDeductResult['status'] != 1){// 授信额度扣款失败了
                        throw new Exception($creditDeductResult['msg']);
                    }
                }
            }

            if($callback && !in_array($push_status, ['已取消','退货退款'])){
                $req_data = [
                    'type'=>'order.status',
                    'data'=>[
                        "customs_time"=>time(),
                        "order_no"=>$_order_no,
                        "order_status"=>$order_status,
                        "source_order_no"=>$_order['orderId']
                    ]
                ];

                $command = new UserMessageQueue();
                $req_result = $command->sendNotice('https://tyj.qekj.net/appinterface/Workwx/test',$req_data);
                if(!$req_result['result']){
                    $msg = '通知失败' . $req_result['data'];
                }else{
                    $msg = 'success';
                    $msg = $req_result['data'];
                }
            }

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail($exception->getMessage());
        }

        return CatchResponse::success($req_data, $msg);
    }

    //候鸟--取消订单
    public function cancelOrder($id,CatchAuth $auth)
    {
        $order = $this->orderModel
            ->field('orderId as source_order_no,
                username,
                user_phone,
                is_pay,
                id_card,
                id_card_front_img,
                id_card_back_img,
                declarer, 
                declarer_id_card,
                source_platform_no,
                amount_freight,
                amount_discount,
                pay_type,
                pay_no, 
                create_time, 
                pay_time, 
                area_id, 
                user_address,
                order_goods,
                tenant_id,
                push_status,
                remark')
            ->find($id);

        if (!$order) {
            return CatchResponse::fail('订单不存在');
        }
        if ($order['push_status'] == '订单已取消') {
            return CatchResponse::fail('订单已取消，不可重复操作');
        }

        $data = $order->toArray();

        dd(333);

        try {
            $result = (new HNOrderApi())->createOrder($data)['data'];
        } catch (\Exception $exception) {
            return CatchResponse::fail($exception->getMessage());
        }

        //dd($result);
        $orderDetailArr = [];
        foreach ($result['order_items'] as $value) {
            $ord = $value;
            $ord['order_id'] = $id;
            $ord['order_no'] = $value['order_no'];
            $ord['source_order_no'] = $value['source_order_no'];
            $ord['tenant_id'] = $tenant_id;
            //$ord['creator_id'] = $creator_id;

            $ord['goods_spu'] = $value['order_goods']['goods_spu'];
            $ord['goods_sku'] = $value['order_goods']['sku_id'];
            $ord['sku_id'] = $value['order_goods']['sku_id'];
            $ord['goods_price'] = $value['order_goods']['goods_price'];
            $ord['goods_num'] = $value['order_goods']['goods_num'];
            $ord['goods_name'] = (new externalGoodsModel)->where('goods_spu', $ord['goods_spu'])->value('goods_name');

            $orderDetailArr[] = $ord;
        }

        Db::startTrans();
        try {
            $order->push_status = '已推送';
            $order->order_items = $result['order_items'];
            $order->save();
            //推送后，创建明细单
            $this->hnOrderDetailModel->saveAll($orderDetailArr);

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail($exception->getMessage());
        }

        return CatchResponse::success([], 'success');
    }

    //候鸟--订单详情
    public function apiOrderDetail_new($id,CatchAuth $auth)
    {
        $user = $auth->user();
        $tenant_id = $user->tenant_id;
        $order_nos = $this->hnOrderDetailModel->where('order_id',$id)->column('order_no');
        $externalGoodsRuleModel = new externalGoodsRuleModel;
        $tenantGoodsRuleModel = new tenantGoodsRuleModel;
        $hnOrderDetailModel = new HnOrderDetail;
        $logisticsModel = new OrderLogistics;

        $orderInfo = (new Order())->findBy($id)->toArray();
        if($orderInfo['express_no']){
            $_goods_money = 0;

            $hnOrderDetail = $hnOrderDetailModel->where('source_order_no',$orderInfo['orderId'])->find();

            $orderStatusOptions = [
                -3=>'异常订单',
                -2=>'是待付款',
                -1=>'已取消',
                0=>'待发货',
//            1=>'已发货、待收货',
                1=>'已发货',
                2=>'已收货',
                3=>'海关审核中|仓库分拣打包中',
                5=>'已完成',
                501=>'退货退款',
            ];
            $orderStatusOptions = array_flip($orderStatusOptions);

            $order_status = array_key_exists($orderInfo['push_status'],$orderStatusOptions) ? $orderStatusOptions[$orderInfo['push_status']] : '未知';

            $result = [
                'coupon_money'=>$hnOrderDetail['coupon_money'],
                'customs_time'=>$hnOrderDetail['created_at'],
                'deliver_money'=>$hnOrderDetail['deliver_money'],
                'delivery_time'=>$hnOrderDetail['created_at'],
                'discount_money'=>$hnOrderDetail['discount_money'],
                'except_reason'=>null,
                'goods_money'=>$hnOrderDetail['tenant_goods_money'],
                'order_no'=>$hnOrderDetail['order_no'],
                'order_status'=>$order_status,
                'real_total_money'=>$hnOrderDetail['tenant_total_money'],
                'source_order_no'=>$hnOrderDetail['source_order_no'],
                'tax_difference_money'=>$hnOrderDetail['tax_difference_money']
            ];

            foreach ($orderInfo['order_goods'] as $key => &$value){
                $_value = [];
                $goods_info = (new tenantGoodsModel())->where('goods_spu',$value['goods_spu'])->where('tenant_id',$orderInfo['tenant_id'])->find();
                $goods_rule_info = (new tenantGoodsRuleModel())->where('goods_sku',$value['sku_id'])->where('tenant_id',$orderInfo['tenant_id'])->find();
                $_value['goods_img'] =  $goods_info['goods_img'];
                $_value['goods_money'] =  $hnOrderDetail['tenant_goods_money'];
                $_value['goods_name'] =  $hnOrderDetail['goods_name'];
                $_value['goods_num'] =  $hnOrderDetail['goods_num'];
                $_value['goods_spu'] =  $hnOrderDetail['goods_spu'];
                $_value['goods_type'] =  $goods_info['trade_type_name'];
                $_value['sku_id'] =  $goods_rule_info['goods_sku'];
                $_value['spec_sku_name'] =  $goods_rule_info['sku_name'];
                $_value['trade_type_id'] =  $goods_rule_info['trade_type_id'];
                $value = $_value;
            }
            $result['order_goods'] = $orderInfo['order_goods'];

            $result['express_info'] = (new OrderLogistics())->where('order_id',$orderInfo['orderId'])->select()->toArray();
            foreach ($result['express_info'] as $key => &$value){
                $_value = [];
                $_value['track_info'] = json_encode([]);
                $_value['express_code'] = $value['express_code'];
//                $_value['express_id'] = $value['express_code'];
                $_value['express_name'] = $value['express_name'];
                $_value['express_no'] = $value['express_no'];
                $value= $_value;
            }

            $return[] = $result;

            return CatchResponse::success($return);
        }

        $orderListResult = (new OrderSon)->where('orderId',$orderInfo['orderId'])->select();
        if (!$orderListResult) {
            $orderListResult = [];
        }else{
            $orderListResult =  $orderListResult->toArray();
        }

        $res = [];

//        print_r($orderListResult);


        foreach ($orderListResult as $_order){
//            print_r($_order['orderlistId']);
//            $hnInfo = $hnOrderDetailModel->where([
//                'source_order_no'=>$_order['orderlistId'],
//            ])->find();

            //同一个订单会拆单
            $hnInfo_arr = $hnOrderDetailModel->where([
                'source_order_no'=>$_order['orderlistId'],
            ])->select();


            if(!$hnInfo_arr) continue;
            $hnInfo_arr = $hnInfo_arr->toArray();

            foreach ($hnInfo_arr as $hnInfo){

                $mainOrderInfo = (new Order)->where('orderId',$_order['orderId'])->find();

                $_data  = [
                    "order_id"=>'' ,
                    "order_no"=>$hnInfo['order_no'],
                    "source_order_no"=>$_order['orderId'],
                    "username"=>$mainOrderInfo['contactName'],
                    "phone"=> $mainOrderInfo['contactMobile'],
                    "id_card"=> "",
                    "id_card_back_img"=>"",
                    "id_card_front_img"=> "",
                    "associated_path"=> $mainOrderInfo['contactAddr'],
                    "address"=> $mainOrderInfo['detailAddr'],
                    "customs_time"=> time(),
                    "delivery_time"=> time(),
                    "receive_time"=> 0,
                    "cancel_order_time"=> 0,
                    "cancel_reason"=> null,
                    "except_reason"=>null,
                    "is_refund"=>0,
                    "refund_type"=> 0,
                    "goods_money"=>$hnInfo['tenant_goods_money'],
                    "deliver_money"=> "0.00",
                    "discount_money"=> "0.00",
                    "coupon_money"=> "0.00",
                    "tax_difference_money"=> "0.00",
                    "real_total_money"=> $hnInfo['tenant_total_money'],
                    "remark"=> "",
                ];

                $_data['order_goods'][] = [
                    "goods_name"=>$hnInfo['goods_name'],
                    "goods_num"=>$hnInfo['goods_num'],
                    "goods_type"=>$_order['trade_type_name'],
                    "goods_img"=> $_order['headImg'],
                    "spec_sku_name"=>$_order['sku_name'],
                    "sku_id"=> $hnInfo['sku_id'],
                    "goods_money"=>$hnInfo['tenant_goods_price'],
                    "goods_spu"=>$hnInfo['goods_spu'],
                    "trade_type_id"=>''
                ];

                $express_info = $logisticsModel
                    ->distinct(true)
                    ->field('express_no,express_name,express_code')
//                    ->where('order_id',$_order['orderlistId'])
                    ->where('order_no',$hnInfo['order_no'])
                    ->select();
                if(empty($express_info)) {
                    $express_info = [];
                }else{
                    $express_info =  $express_info->toArray();
                }

                $_data['express_info'] = $express_info;
                $_data['order_status'] = $hnInfo['mall_order_status'];

//            $_data['api_post_status'] = $_order['api_post_status'];
                $res[] = $_data;

            }


        }

        return CatchResponse::success($res);
    }

    //候鸟--订单详情
    public function apiOrderDetail($id,CatchAuth $auth)
    {
        $user = $auth->user();
        $tenant_id = $user->tenant_id;
        $order_nos = $this->hnOrderDetailModel->where('order_id',$id)->column('order_no');
        $externalGoodsRuleModel = new externalGoodsRuleModel;
        $tenantGoodsRuleModel = new tenantGoodsRuleModel;
        $hnOrderDetailModel = new HnOrderDetail;

        $orderInfo = (new Order())->findBy($id)->toArray();
        if($orderInfo['express_no']){
            $_goods_money = 0;

            $hnOrderDetail = $hnOrderDetailModel->where('source_order_no',$orderInfo['orderId'])->find();

            $orderStatusOptions = [
                -3=>'异常订单',
                -2=>'是待付款',
                -1=>'已取消',
                0=>'待发货',
//            1=>'已发货、待收货',
                1=>'已发货',
                2=>'已收货',
                3=>'海关审核中|仓库分拣打包中',
                5=>'已完成',
                501=>'退货退款',
            ];
            $orderStatusOptions = array_flip($orderStatusOptions);

            $order_status = array_key_exists($orderInfo['push_status'],$orderStatusOptions) ? $orderStatusOptions[$orderInfo['push_status']] : '未知';

            $result = [
                'coupon_money'=>$hnOrderDetail['coupon_money'],
                'customs_time'=>$hnOrderDetail['created_at'],
                'deliver_money'=>$hnOrderDetail['deliver_money'],
                'delivery_time'=>$hnOrderDetail['created_at'],
                'discount_money'=>$hnOrderDetail['discount_money'],
                'except_reason'=>null,
                'goods_money'=>$hnOrderDetail['tenant_goods_money'],
                'order_no'=>$hnOrderDetail['order_no'],
                'order_status'=>$order_status,
                'real_total_money'=>$hnOrderDetail['tenant_total_money'],
                'source_order_no'=>$hnOrderDetail['source_order_no'],
                'tax_difference_money'=>$hnOrderDetail['tax_difference_money']
            ];

            foreach ($orderInfo['order_goods'] as $key => &$value){
                $_value = [];
                $goods_info = (new tenantGoodsModel())->where('goods_spu',$value['goods_spu'])->where('tenant_id',$orderInfo['tenant_id'])->find();
                $goods_rule_info = (new tenantGoodsRuleModel())->where('goods_sku',$value['sku_id'])->where('tenant_id',$orderInfo['tenant_id'])->find();
                $_value['goods_img'] =  $goods_info['goods_img'];
                $_value['goods_money'] =  $hnOrderDetail['tenant_goods_money'];
                $_value['goods_name'] =  $hnOrderDetail['goods_name'];
                $_value['goods_num'] =  $hnOrderDetail['goods_num'];
                $_value['goods_spu'] =  $hnOrderDetail['goods_spu'];
                $_value['goods_type'] =  $goods_info['trade_type_name'];
                $_value['sku_id'] =  $goods_rule_info['goods_sku'];
                $_value['spec_sku_name'] =  $goods_rule_info['sku_name'];
                $_value['trade_type_id'] =  $goods_rule_info['trade_type_id'];
                $value = $_value;
            }
            $result['order_goods'] = $orderInfo['order_goods'];

            $result['express_info'] = (new OrderLogistics())->where('order_id',$orderInfo['orderId'])->select()->toArray();
            foreach ($result['express_info'] as $key => &$value){
                $_value = [];
                $_value['track_info'] = json_encode([]);
                $_value['express_code'] = $value['express_code'];
//                $_value['express_id'] = $value['express_code'];
                $_value['express_name'] = $value['express_name'];
                $_value['express_no'] = $value['express_no'];
                $value= $_value;
            }

            $return[] = $result;

            return CatchResponse::success($return);
        }

        $return = [];

        try {
            foreach ($order_nos as $key => $order_no){
                $data = [
                    'order_no'=>$order_no
                ];

                $result = (new HNOrderApi())->info($data)['data'];

                $_goods_money = 0;
                foreach ($result['order_goods'] as &$vv){
////                    unset($vv['goods_money']);
//                    $rule_money = $tenantGoodsRuleModel->where([
//                        'goods_spu'=>$vv['goods_spu'],
//                        'goods_sku'=>$vv['sku_id']
//                    ])->order('id','desc')->value('sku_price');

                    $rule_money_where = [
                        'order_no'=>$order_no,
                        'goods_spu'=>$vv['goods_spu'],
                        'sku_id'=>$vv['sku_id']
                    ];
                    if($tenant_id != 0){
                        $rule_money_where['tenant_id'] = $tenant_id;
                    }

//                    $rule_money = $hnOrderDetailModel->where($rule_money_where)->value('goods_price');
//                    if(10050 == $tenant_id){
//                        $rule_money = round($rule_money * 1.1);
//                    }elseif (10043 == $tenant_id){
//                        $rule_money = round($rule_money * 1.29);
//                    }else{
//                        $rule_money = round($rule_money * 1.1);
//                    }

                    $rule_money = $hnOrderDetailModel->where($rule_money_where)->value('tenant_goods_price');

                    $vv['goods_money'] = $rule_money;
                    $_goods_money += $rule_money * $vv['goods_num'];
                }

//                "goods_money": "61.50", //商品总额
//                "deliver_money": "0.00", //运费金额
//                "discount_money": "3.00", //优惠金额
//                "coupon_money": "0.00", //优惠券金额
//                "tax_difference_money": "0.00", //税差金额
//                "real_total_money": "58.50", //实付金额
                unset($result['pay_no']);
                unset($result['pay_type']);
                unset($result['pay_time']);
                unset($result['create_time']);

                $result['goods_money'] = number_format($_goods_money,2,'.','');
                $result['real_total_money'] = real_total_money($result['goods_money'], $result['deliver_money'],$result['discount_money'],$result['coupon_money'],$result['tax_difference_money']);

                if(!empty($result['express_info'])){}

                //返回数据
                $return[$key] = $result;
            }

        } catch (\Exception $exception) {
            return CatchResponse::fail($exception->getMessage());
        }

        return CatchResponse::success($return);
    }

    //菜鸟--交易出库单下发
    public function apiSaleOrder($id,CatchAuth $auth){
        $user = $auth->user();

        $order  = $this->orderModel
            ->field([
                'push_status',
                'ownerUserId',
                'businessUnitId',
                'externalOrderCode',
                'orderType',
                'storeCode',
                'externalShopId',
                'externalShopName',
                'orderSource',
                'orderSubSource',
                'orderCreateTime',
                'orderPayTime',
                'saleMode',
                'receiverInfo',
                'senderInfo',
                'refunderInfo',
                'orderItemList',
                'orderAmountInfo',
                'customsDeclareInfo',
                'extendFields',
                'remark',
                'serviceId',
                'departureInfo',
                'sellerRemark',
                'buyerRemark',
                'logisticsServices',
                'cnOrderCode',
                'mailNo',
                'partnerCode',
                'partnerName',
                'packageInfo',
            ])
            ->find($id);

        if(!$order){
            return CatchResponse::fail('订单不存在');
        }
        if($order['push_status'] !== '未推送'){
            return CatchResponse::fail('订单已经推送，不可重复操作');
        }

        $data = $order->toArray();

        unset($data['_ext_data']);

//        $data['receiverInfo'] = json_decode($data['receiverInfo'],true);
//        $data['senderInfo'] = json_decode($data['senderInfo'],true);
//        $data['refunderInfo'] = json_decode($data['refunderInfo'],true);
//        $data['orderItemList'] = json_decode($data['orderItemList'],true);
//        $data['orderAmountInfo'] = json_decode($data['orderAmountInfo'],true);
//        $data['customsDeclareInfo'] = json_decode($data['customsDeclareInfo'],true);
//        //--------//
//        $data['extendFields'] = json_decode($data['extendFields'],true);
//        $data['departureInfo'] = json_decode($data['departureInfo'],true);
//        $data['logisticsServices'] = json_decode($data['logisticsServices'],true);

        foreach ($data as $key => $value){
            //过滤空数组
            if(is_array($value) && 0 == count($value)){
                unset($data[$key]);
            }
            //过滤空字符串
            if($value == ''){
                unset($data[$key]);
            }
            //过滤一些其他字段

        }
//        dd($data);

        try {
            $cainiaoApi = new Link;
            $result =  $cainiaoApi->GLOBAL_SALE_ORDER_NOTIFY($data);

            if($result['success'] == 'true'){//成功
                $order->cnOrderCode = $result['cnOrderCode'];
                $order->push_status = '已推送';
                $order->save();
            }else{
                return CatchResponse::fail( '推送失败');
            }
        } catch (\Exception $e) {
            return CatchResponse::fail( $e->getMessage());
        }

        return CatchResponse::success($result,'下单成功');
    }

    //菜鸟--查询最新订单消息
    public function queryOrder($id,CatchAuth $auth, Request $request){
        $user = $auth->user();

        $order  = $this->orderModel
            ->field([
                    'push_status',
                    'ownerUserId',
                    'businessUnitId',
                    'externalOrderCode',
                    'orderType',
                    'storeCode',
                    'externalShopId',
                    'externalShopName',
                    'orderSource',
                    'orderSubSource',
                    'orderCreateTime',
                    'orderPayTime',
                    'saleMode',
                    'receiverInfo',
                    'senderInfo',
                    'refunderInfo',
                    'orderItemList',
                    'orderAmountInfo',
                    'customsDeclareInfo',
                    'extendFields',
                    'remark',
                    'serviceId',
                    'departureInfo',
                    'sellerRemark',
                    'buyerRemark',
                    'logisticsServices',
                    'cnOrderCode',
                    'mailNo',
                    'partnerCode',
                    'partnerName',
                    'packageInfo'
            ])
            ->find($id);

        if(!$order){
            return CatchResponse::fail('订单不存在');
        }

        if($order['push_status'] == '未推送'){
            return CatchResponse::success([]);
        }

        $data = [
            'userId'=>$order['ownerUserId'],
            'lgOrderCode'=>$order['cnOrderCode']
        ];

        try {
            $cainiaoApi = new Link;
            $result =  $cainiaoApi->CROSSBORDER_LOGISTICS_DETAIL_QUERY($data);


            if($result['success'] != 'true'){
                return CatchResponse::fail( '查询失败');
            }

//            if($result['success'] == 'true'){//成功
//
//                $order->push_status = $result['nodeList'][0]['packageStatus']['logisticStatusDesc'];
//                $order->mailNo = $result['nodeList'][0]['mailNo'];
//                $order->partnerCode = $result['nodeList'][0]['partnerList'][0]['partnerCode'];
//                $order->partnerName = $result['nodeList'][0]['partnerList'][0]['partnerName'];
//                $order->save();
//            }else{
//                return CatchResponse::fail( '查询失败');
//            }

        } catch (\Exception $e) {
            return CatchResponse::fail($e->getMessage());
        }

        return CatchResponse::success($result,'查询成功');
    }

    //菜鸟--修改支付单&身份号码
    public function modifyInfo($id,CatchAuth $auth, Request $request){
        $order  = $this->orderModel
            ->field('externalOrderCode,ownerUserId as merchantId,externalShopId as extUserId,orderSource,customsDeclareInfo,cnOrderCode,push_status')
            ->find($id);

        if(!$order){
            return CatchResponse::fail('订单不存在');
        }

        if($order['push_status'] == '未推送'){
            return CatchResponse::fail('订单暂未推送,无法修改');
        }


        $orderData = $order->toArray();

        switch ($order['customsDeclareInfo']['payChannel']){
            case 'XSZF':
                $orderData['payType'] = '17';
                break;
            case 'ALIPAY':
                $orderData['payType'] ='01';
                break;
            case 'WEIXINPAY':
                $orderData['payType'] ='02';
                break;
            default:
                $orderData['payType'] ='01';
        }

        $customsDeclareInfo = $orderData['customsDeclareInfo'];
        unset($orderData['customsDeclareInfo']);

        $requestData = array_filter($request->only(['buyerName','buyerIDNo','payOrderId','buyerIDCardFrontPic','idCardBackPicUrlIndex']));
        $data = array_filter(array_merge($requestData,$orderData));

        //dd(array_keys($requestData));

        try {
            $cainiaoApi = new Link;
            $result =  $cainiaoApi->CROSSBORDER_ORDER_INFO_MODIFY($data);

            if($result['success'] != 'true'){
                return CatchResponse::fail( '修改失败' . $result['errorMsg']);
            }else{
                $saveData = array_merge($customsDeclareInfo,$requestData);

                $order->buyerName = $requestData['buyerName'];//购买人
                $order->ConsigneeCode = $requestData['buyerIDNo'];//身份证号
//                $order->payOrderNo = $requestData['payOrderNo'];//支付单号
                $order->customsDeclareInfo = $saveData;
                $order->save();
                //$order->allowField(array_keys($requestData))->save($requestData);
            }
        } catch (\Exception $e) {
            return CatchResponse::fail($e->getMessage());
        }

        return CatchResponse::success($result,'修改成功');
    }

    protected function check_fields($params, $fields, $back){
        if(!is_array($params)){
            return '数据格式错误';

        }
        $err = false;
        $deal_params = [];

        foreach ($fields as $value) {
            if(!array_key_exists($value, $params)){
                if($back){
                    $err = '缺少字段'.$value;
                    break;
                }

            }else{
                $deal_params[$value] = $params[$value];

            }

        }
        if($err === false){
            return $deal_params;
        }else{
            return $err;
        }

    }


    public function importExcl($fields, $file, callable $callable)
    {
        $excel = new class($fields) extends Reader {
            protected $fields;

            public function __construct($fields)
            {
                $this->fields = $fields;
            }

            public function headers()
            {
                // TODO: Implement headers() method.
                return $this->fields;
            }
        };
        $excel->import($file)->then(function ($data) use ($callable) {
            $callable($data);
        });

    }

    public function exportOrders(Request $request, Excel $excel,  tenantOrdersExport $tenantOrdersExport){

        return CatchResponse::success($excel->save($tenantOrdersExport, 'export/tenantOrdersExport'));
    }

    public function query1(){

        $data = '{"queryType":"1","orderType":"1","oldMerOrderId":"240123195819356701","startTime":"","endTime":"","page":""}';

        $data = json_decode($data,true);


        $keys = ['queryType','orderType','oldMerOrderId','startTime','endTime','page'];
        $value = $this->check_fields($data, $keys, true);//验证字段
        //判断参数
        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];
        }

        if(1 == $data['queryType']){//单笔订单
            if(empty($data['oldMerOrderId']))  return [ 'code'=>Code::FAILED , 'msg'=> 'oldMerOrderId不能为空'];

        }

        $order  = (new XsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('merOrderId',$data['oldMerOrderId'])
            ->find();

        if(!$order){
            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['oldMerOrderId']}不存在"];
        }

        $xinshengApi = new Pay($this->_par);

        try {
            $result = $xinshengApi->orderQuery($data);

            $now = date('Y-m-d H:i:s');
            $ip = request()->ip();
            $log_path = "a.txt";
//            if(!is_dir($log_path)) {
//                mkdir($log_path,0755,true);
//            }

           $redis = Service::connectRedis();
           $redis->lPush('aaaa',json_encode($result));

            file_put_contents($log_path,json_encode($result) . "\r\n");

//            error_log( , 3,$destination);

            return CatchResponse::success( $result['content']);
        }catch (\Exception $e ){
            return CatchResponse::fail($e->getMessage());
        }
    }


}